<template>
  <div>
    <el-table :data="tableData" border style="width: 100%">
      <el-table-column prop="prid" label="就诊编号" width="80px" header-align="center" align="center"></el-table-column>
      <el-table-column prop="pname" label="病人姓名" width="100px" header-align="center" align="center"></el-table-column>
      <el-table-column prop="sympotm" label="症状" width="100px" header-align="center" align="center"></el-table-column>
      <el-table-column prop="mdname" label="药品名称" width="150px" header-align="center"></el-table-column>
      <el-table-column prop="mednum" label="药品数量" width="200px" header-align="center" align="center"></el-table-column>
      <el-table-column prop="description" label="用法" width="200px" header-align="center"></el-table-column>
      <el-table-column prop="price" label="单价" width="100px" header-align="center"></el-table-column>
      <el-table-column prop="medic" label="总价" width="100px" header-align="center"></el-table-column>
      <el-table-column label="操作" width="83px" header-align="center">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="openDialog(scope.row.prid)">开药</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
      :current-page="pageInfo.pageNum" :page-sizes="[5, 10, 15, 20]" :page-size="pageInfo.pageSize"
      layout="total, sizes, prev, pager, next, jumper" :total="pageInfo.total">
    </el-pagination>
    <el-dialog title="开药" :visible.sync="dialogVisible" width="50%">
      <el-form :model="form" label-width="100px">
        <el-form-item label="药品名称">
          <el-select v-model="form.mdname" placeholder="请选择药品" @change="loadMedicineDetail">
            <el-option v-for="item in medicineList" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="药品数量">
          <el-input v-model.number="form.mednum" @input="calculatemedic"></el-input>
        </el-form-item>
        <el-form-item label="用法">
          <el-input v-model="form.description"></el-input>
        </el-form-item>
        <el-form-item label="单价">
          <el-input v-model="form.price" disabled></el-input>
        </el-form-item>
        <el-form-item label="总价">
          <el-input v-model="form.medic" disabled></el-input>
        </el-form-item>
        <el-form-item label="库存数量">
          <el-input v-model="form.mdnum" disabled></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirm">确认</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>

export default {
  data() {
    return {
      tableData: [],
      dialogVisible: false,
      form: {
        prid: '',
        mdname: '',
        mednum: '',
        description: '',
        medid: '',
        price: '',
        medic: '',
        mdnum: ''
      },
      currentPrid: '',
      medicineList: [],
      pageInfo: {
        pageNum: 1,
        pageSize: 5
      },
    }
  },
  methods: {
    handleSizeChange(val) {
      this.pageInfo.pageSize = val;
      this.list();
    },
    handleCurrentChange(val) {
      this.pageInfo.pageNum = val;
      this.list();
    },
    updateStock(medid, mednum) {
      this.$axios.get("medicion/updateStock?medid=" + medid + "&mednum=" + mednum)
        .then((stockResult) => {
          let stockVo = stockResult.data;
          if (stockVo.code == 200) {
            this.dialogVisible = false;
            this.list(); // 刷新列表
            this.$message.success('库存已更新');
          } else if (stockVo.code == 500 && stockVo.message == '库存不足') {
            this.$message.error('库存不足,无法开药');
          } else {
            this.$message.error('更新库存失败: ' + stockVo.message);

          }
        })
        .catch((err) => {
          console.error('更新库存请求失败:', err);
          this.$message.error('更新库存失败');
        });
    },
    loadMedicineDetail(mdname) {
      const selectedMedicine = this.medicineList.find(item => item.value === mdname);
      if (selectedMedicine) {
        this.form.medid = selectedMedicine.medid; // 将 medid 存储在 form 中
        this.form.price = selectedMedicine.price; // 将单价存储在 form 中
        this.form.mdnum = selectedMedicine.mdnum; // 将库存数量存储在 form 中
        this.calculatemedic(); // 计算总价
        console.log('Selected medicine:', mdname, 'with medid:', this.form.medid);
      } else {
        console.log('Medicine not found:', mdname);
      }
    },
    loadMedicineList() {
      this.$axios.get("medicion/findAll1")
        .then((result) => {
          let vo = result.data;
          if (vo.code == 200) {
            this.medicineList = vo.data.map((item) => {
              return {
                value: item.mdname,
                label: item.mdname,
                medid: item.medid,
                price: item.price,
                mdnum: item.mdnum,
              }
            });
          }
        }).catch((err) => {
          console.log(err);
        });
    },
    calculatemedic() {
      if (this.form.mednum && this.form.price) {
        this.form.medic = (this.form.mednum * this.form.price).toFixed(2); // 计算总价并保留两位小数
      } else {
        this.form.medic = '';
      }
    },
    confirm() {
      if (this.form.mednum > this.form.mdnum) {
        this.$message.error('库存不足,无法开药');
        return;
      }

      this.$axios.post("prescription/add", this.form)
        .then((result) => {
          let vo = result.data;
          if (vo.code == 200) {
            this.updateStock(this.form.medid, this.form.mednum);
            this.dialogVisible = false;

            this.list(); // 刷新列表
            this.$message.success('开药成功');
          } else {
            this.$message.error('开药失败');
          }
        }).catch((err) => {
          console.log(err);
          this.$message.error('开药失败');
        });
    },

    openDialog(prid) {
      this.dialogVisible = true;
      this.form.prid = prid;
      this.form.mdname = ''; // 清空药品名称
      this.form.mednum = ''; // 清空药品数量
      this.form.description = ''; // 清空用法
      this.form.medid = ''; // 清空 medid
      this.form.price = ''; // 清空 price
      this.form.medic = ''; // 清空 zongprice
      this.form.mdnum = ''; // 清空 stocknum
      this.loadMedicineList(); // 加载药品列表
    },
    list() {
      this.$axios.get("prescription/findAll?pageNum=" + this.pageInfo.pageNum + "&pageSize=" + this.pageInfo.pageSize)
        .then((result) => {
          let vo = result.data;
          if (vo.code == 200) {
            this.tableData = vo.data.list;
            this.pageInfo = vo.data;
          }
        }).catch((err) => {
          console.log(err);
        });
    }},
    mounted() {
      this.list();
    }
  }
</script>